package com.restkeeper.store.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.restkeeper.exception.BussinessException;
import com.restkeeper.store.entity.Credit;
import com.restkeeper.store.entity.CreditRepayment;
import com.restkeeper.store.mapper.CreditRepaymentMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 还款记录表 服务实现类
 * </p>
 */
@Slf4j
@Component
@Service(version = "1.0.0",protocol = "dubbo")
public class CreditRepaymentServiceImpl extends ServiceImpl<CreditRepaymentMapper, CreditRepayment> implements ICreditRepaymentService {

    @Autowired
    private ICreditService creditService;

    /**
     * 挂账还款
     * @param creditRepayment
     * @return
     */
    @Override
    @Transactional
    public boolean repayment(CreditRepayment creditRepayment) {

        // todo 看了参考代码才理清挂账金额（欠款金额）与还款金额在表中的对应关系
        // 获取当前用户还款总额
        Integer repaymentAmount = creditRepayment.getRepaymentAmount();
        // 获取当前挂账信息
        Credit credit = creditService.getById(creditRepayment.getCreditId());
        // 若还款总额超出了挂账金额，则属于非法操作
        if (credit.getCreditAmount() - repaymentAmount < 0){
            throw new BussinessException("还款金额超过挂账金额");
        }

        // 新增还款记录
        this.save(creditRepayment);

        // 修改挂账欠款信息
        credit.setCreditAmount(credit.getCreditAmount() - repaymentAmount);

        // 记录总还款金额
        credit.setTotalRepaymentAmmount(credit.getTotalRepaymentAmmount() + repaymentAmount);

        return creditService.saveOrUpdate(credit);
    }
}
